var dictKeyArray = [];
var playr;
layui.use(['element','table','form','layer','laydate'], function(){
    var table = layui.table,
    form = layui.form,
    $ = layui.jquery,
    laydate = layui.laydate,
    layer = layui.layer;

    table.render({
        elem: '#deviceRecordTable'
        ,url:'/cdysylives/listCamera'
        ,title: '摄像头列表'
        ,method: 'get'
        ,where: {}
        ,cols: [[
            {field: 'xh',type:'numbers', title: '序号',}
            ,{field:'deviceSerial', title:'设备序列号',align:'center'}
            ,{field:'channelNo', title:'通道号',align:'center'}
            ,{field:'channelName', title:'通道名',align:'center'}
            ,{field: 'status', title: '设备状态', align:'center',templet: function (d) {
                    return parseStatus(d.status);
                }}
            ,{field: 'isEncrypt', title: '是否加密', align:'center',templet: function (d) {
                    return parseEncrypt(d.isEncrypt);
                }}
            ,{field: 'videoLevel', title: '视频质量', align:'center',templet: function (d) {
                    return parseQuality(d.videoLevel);
                }}
            ,{field: 'isAdd', title: '显示状态', align:'center',templet: function (d) {
                    return parseShow(d.isAdd);
                }}
            ,{field: 'picUrl', title: '图片地址', align:'center',templet:function (d) {
                    if(d.picUrl){
                        return '<img onclick="previewImg(this)" style="cursor: pointer" width="30" height="25" src="'+d.picUrl+'"/>';
                    }
                    return "";
                }}
            , {field: 'right', title: '操作', align:'center',width:200,templet:function(data){
                    return '<a class="layui-btn layui-btn-xs" lay-event="monitor1">监控(流畅)</a>' +
                        '<a class="layui-btn layui-btn-xs" lay-event="monitor2">监控(高清)</a>';
                }
            }
        ]]
        ,page: false
    });
    table.on('tool(deviceRecordTable)', function(obj){
        let data = obj.data;
        switch (obj.event){
            case 'monitor1':
                getLiveAddress(data.deviceSerial,"2",data.channelNo);//流畅
                break;
            case 'monitor2':
                getLiveAddress(data.deviceSerial,"1",data.channelNo);//高清
                break;
        }
    });

    function getLiveAddress(deviceSerial,quality,channelNo) {
        var index = layer.load();
        $.get("/cdysylives/getLiveAddress", {"deviceSerial":deviceSerial,"quality":quality,"channelNo":channelNo}, function (result) {
            layer.close(index);
            if (result.resultCode === '000') {
                var urlToken = result.resultContent;
                if(urlToken){
                    $("#url").val(urlToken.url);
                    $("#accessToken").val(urlToken.token);
                    layer.open({
                        type: 1
                        , title: '监控模式'
                        , shadeClose: true
                        , area: ['99%', '99%']
                        , content: $('#monitorWindow'),
                        cancel: function(){
                            if(playr){
                                playr.stop();
                                $("#monitorWindow").find("#video-container").remove();
                            }
                        }
                    });
                }else {layer.msg("参数有误", {icon: 5});}
            } else {
                layer.msg(result.resultDesc, {icon: 5});
            }
        });
    }

    $("#init").on('click',function (){
        var token = $("#accessToken").val();
        var url = $("#url").val();
        if(!token || !url){return layer.msg("获取播放地址失败",{icon:5})}
        let videoDiv = $("#monitorWindow").find("#video-container");
        if(videoDiv){
            videoDiv.remove();
        }
        $("#monitorWindow").append('<div id="video-container" style="width: 600px;"></div>');
        playr = new EZUIKit.EZUIKitPlayer({
            id: 'video-container', // 视频容器ID
            accessToken: token,
            url: url,
            template: 'simple', // simple - 极简版;standard-标准版;security - 安防版(预览回放);voice-语音版；
            autoplay: true,
            // 视频上方头部控件
            //header: ['capturePicture','save','zoom'],            // 如果templete参数不为simple,该字段将被覆盖
            // 视频下方底部控件
            //footer: ['talk','broadcast','hd','fullScreen'],      // 如果template参数不为simple,该字段将被覆盖
            audio: 1, // 是否默认开启声音 0 - 关闭 1 - 开启
            plugin: ['talk'],                       // 加载插件，talk-对讲
            openSoundCallBack: (data) => console.log("开启声音回调",data),
            closeSoundCallBack: (data) => console.log("关闭声音回调",data),
            startSaveCallBack: (data) => console.log("开始录像回调",data),
            stopSaveCallBack: (data) => console.log("录像回调",data),
            capturePictureCallBack: (data) => console.log("截图成功回调",data),
            fullScreenCallBack: (data) => console.log("全屏回调",data),
            getOSDTimeCallBack: (data) => console.log("获取OSDTime回调",data),
            handleSuccess: (data) = function(){console.log("播放成功回调",data)},
            handleError: (data) => console.log("播放失败回调",data),
            width:600,
            height:400,
        });
    });
    $("#play").on('click',function (){
        if(!playr){return layer.msg("请先初始化",{icon:5})}
        playr.play();
    });
    $("#stop").on('click',function (){
        if(!playr){return layer.msg("请先初始化",{icon:5})}
        playr.stop();
    });

});
function parseStatus(status) {
    switch (Number(status)) {
        case 0: return "离线";
        case 1: return "在线";
        default: return "未知";
    }
}
function parseEncrypt(isEncrypt) {
    switch (Number(isEncrypt)) {
        case 0: return "不加密";
        case 1: return "加密";
        default: return "-";
    }
}
function parseQuality(videoLevel) {
    switch (Number(videoLevel)) {
        case 0: return "流畅";
        case 1: return "均衡";
        case 2: return "高清";
        case 3: return "超清";
        default: return "-";
    }
}
function parseShow(isAdd) {
    switch (Number(isAdd)) {
        case 0: return "隐藏";
        case 1: return "显示";
        default: return "-";
    }
}

function reload(){
    location.reload();
}
function formatTime(datetime,fmt) {
    if (parseInt(datetime)==datetime) {
        if (datetime.length==10) {
            datetime=parseInt(datetime)*1000;
        } else if(datetime.length==13) {
            datetime=parseInt(datetime);
        }
    }
    datetime=new Date(datetime);
    var o = {
        "M+" : datetime.getMonth()+1,                 //月份
        "d+" : datetime.getDate(),                    //日
        "h+" : datetime.getHours(),                   //小时
        "m+" : datetime.getMinutes(),                 //分
        "s+" : datetime.getSeconds(),                 //秒
        "q+" : Math.floor((datetime.getMonth()+3)/3), //季度
        "S"  : datetime.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (datetime.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}
//预览大小根据原图的大小决定弹窗的大小
let imgDiv;
function previewImg(obj) {
    var img = new Image();
    img.src = obj.src;
    var height = img.height + 50; //获取图片高度
    var width = img.width; //获取图片宽度
    var imgHtml = "<img onclick='closeLayer()' src='" + obj.src + "' width='100%' height='100%'/>";
    //弹出层
    imgDiv = layui.layer.open({
        type: 1,
        shade: 0.8,
        offset: 'auto',
        area: ['100%', '100%'],
        shadeClose: true,
        scrollbar: false,
        title: "抓拍图片预览",
        content: imgHtml,
        cancel: function () {
        }
    });
}
function closeLayer() {
    if(imgDiv){
        layui.layer.close(imgDiv);
    }
}